//
//  YD_CommonTool.m
//  StudyLawApp
//
//  Created by 如沐春风 on 2020/5/13.
//  Copyright © 2020 永东科技. All rights reserved.
//

#import "YD_CommonTool.h"

static YD_CommonTool *instance = nil;
@implementation YD_CommonTool
+(instancetype)Instance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[YD_CommonTool alloc] init];
    });
    return instance;
}



/**
 * 计算文本尺寸
 */
+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font {
    return [text sizeWithAttributes:@{NSFontAttributeName: font}];
}
/**
 *  计算限定宽度文本尺寸
 */
+ (CGSize)sizeWithText:(NSString *)text font:(UIFont *)font maxW:(CGFloat)maxW {
    CGSize size = CGSizeMake(maxW, CGFLOAT_MAX);
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    NSDictionary *attrs = @{NSFontAttributeName : font};
    return [text boundingRectWithSize:size options:options attributes:attrs context:nil].size;
}
/**
 *  计算限定宽度文本尺寸附加行高
 */
+ (CGFloat)getSpaceLabelHeight:(NSString*)str lineSpacing:(CGFloat )lineSpacing Font:(UIFont*)font Width:(CGFloat)width {
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineBreakMode =NSLineBreakByCharWrapping;
    paraStyle.alignment =NSTextAlignmentLeft;
    /**行高 */
    paraStyle.lineSpacing = lineSpacing;
//    paraStyle.hyphenationFactor =1.0;
//    paraStyle.firstLineHeadIndent =0.0;
//    paraStyle.paragraphSpacingBefore =0.0;
//    paraStyle.headIndent =0;
//    paraStyle.tailIndent =0;
    NSDictionary *dic = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:paraStyle/*,NSKernAttributeName:@1.5f*/};
    CGSize size = [str boundingRectWithSize:CGSizeMake(width,CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    return size.height;
}
/**
 *时间戳转时间
 */
+ (NSString *)timeStampStringToLocalTime:(NSString *)timeStampString{
    NSTimeInterval interval    =[timeStampString doubleValue] / 1000.0;
    NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString       = [formatter stringFromDate: date];
    return dateString;
}

+ (BOOL)isNum:(NSString *)checkedNumString {
    checkedNumString = [checkedNumString stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(checkedNumString.length > 0) {
        return NO;
    }
    return YES;
}




//比较两个日期的大小
+ (BOOL)compareDate:(NSDate*)stary withDate:(NSDate*)end
{
    NSComparisonResult result = [stary compare: end];
    if (result==NSOrderedSame)
    {
        //相等
        return NO;
    }else if (result == NSOrderedAscending)
    {
        //结束时间大于开始时间
        return YES;
    }else if (result == NSOrderedDescending)
    {
        //结束时间小于开始时间
        return NO;
    }
    return NO;
}

/**
 *设置带行间距的属性字符串
 */
+ (NSMutableAttributedString *)setAttributedStringWithString:(NSString *)aString linespace:(CGFloat )linespace font:(UIFont *)font{
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
        paraStyle.lineBreakMode =NSLineBreakByCharWrapping;
        paraStyle.alignment =NSTextAlignmentLeft;
        /**行高 */
        paraStyle.lineSpacing =linespace;
    //    paraStyle.hyphenationFactor =1.0;
    //    paraStyle.firstLineHeadIndent =0.0;
    //    paraStyle.paragraphSpacingBefore =0.0;
    //    paraStyle.headIndent =0;
    //    paraStyle.tailIndent =0;
        NSDictionary *dic = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:paraStyle/*,NSKernAttributeName:@1.5f*/};
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:aString attributes:dic];
    return attr;
}
//获取当前window
+(UIWindow*)getCurrentWindow{
    if ([[[UIApplication sharedApplication] delegate] window]) {
        return [[[UIApplication sharedApplication] delegate] window];
        
    }else{
        if (@available(iOS 13.0, *)) {
            NSArray *array =[[[UIApplication sharedApplication] connectedScenes] allObjects];
            UIWindowScene * windowScene = (UIWindowScene *)array[0];
            UIWindow * mainWindow = [windowScene valueForKeyPath:@"delegate.window"];
            if (mainWindow) {
                return mainWindow;
            }else{
                return [UIApplication sharedApplication].windows.lastObject;
            }
        }else {
                return [UIApplication sharedApplication].keyWindow;
        }
    }
}


/**
 *获取状态栏高度
 */
+ (CGFloat )getStatusHeight{
    NSSet *set = [[UIApplication sharedApplication] connectedScenes];
    UIWindowScene *windowScene = [set anyObject];
    UIStatusBarManager *statusBarManager2 =  windowScene.statusBarManager;
    CGFloat statusHeight = statusBarManager2.statusBarFrame.size.height;
    return statusHeight;
}




+(CGSize)downloadImageSizeWithURL:(id)imageURL

{

  NSURL* URL = nil;

  if([imageURL isKindOfClass:[NSURL class]]){

    URL = imageURL;

  }

  if([imageURL isKindOfClass:[NSString class]]){

    URL = [NSURL URLWithString:imageURL];

  }

  if(URL == nil)

    return CGSizeZero;

#ifdef dispatch_main_sync_safe

  if([[SDImageCache sharedImageCache] diskImageExistsWithKey:absoluteString])

  {

    UIImage* image = [[SDImageCache sharedImageCache] imageFromMemoryCacheForKey:absoluteString];

    if(!image)

    {

      NSData* data = [[SDImageCache sharedImageCache] performSelector:@selector(diskImageDataBySearchingAllPathsForKey:) withObject:URL.absoluteString];

      image = [UIImage imageWithData:data];

    }

    if(image)

    {

      return image.size;

    }

  }

#endif

  NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1];

  

  NSString* pathExtendsion = [URL.pathExtension lowercaseString];

  CGSize size = CGSizeZero;

  if ([pathExtendsion rangeOfString:@"png"].location != NSNotFound) {

    size = [self downloadPNGImageSizeWithRequest:request];

  }

  else if([pathExtendsion rangeOfString:@"gif"].location != NSNotFound)

  {

    size = [self downloadGIFImageSizeWithRequest:request];

  }

  else{

    size = [self downloadJPGImageSizeWithRequest:request];

  }

  if(CGSizeEqualToSize(CGSizeZero, size))

  {

    NSData* data = [NSData dataWithContentsOfURL:URL];

    UIImage* image = [UIImage imageWithData:data];

    if(image)

    {

      //如果未使用SDWebImage，则忽略；缓存该图片

#ifdef dispatch_main_sync_safe

      [[SDImageCache sharedImageCache] storeImage:image recalculateFromImage:YES imageData:data forKey:URL.absoluteString toDisk:YES];

#endif

      size = image.size;

    }

  }

  //过滤掉不符合大小的图片，大图太大浪费流量，用户体验不好

  if (size.height > 2048 || size.height <= 0 || size.width > 2048 || size.width <= 0 ) {

    return CGSizeZero;

  }

  else

  {

    return size;

  }

}

+(CGSize)downloadPNGImageSizeWithRequest:(NSMutableURLRequest*)request

{

  [request setValue:@"bytes=16-23" forHTTPHeaderField:@"Range"];

  NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

  if(data.length == 8)

  {

    int w1 = 0, w2 = 0, w3 = 0, w4 = 0;

    [data getBytes:&w1 range:NSMakeRange(0, 1)];

    [data getBytes:&w2 range:NSMakeRange(1, 1)];

    [data getBytes:&w3 range:NSMakeRange(2, 1)];

    [data getBytes:&w4 range:NSMakeRange(3, 1)];

    int w = (w1 << 24) + (w2 << 16) + (w3 << 8) + w4;

    int h1 = 0, h2 = 0, h3 = 0, h4 = 0;

    [data getBytes:&h1 range:NSMakeRange(4, 1)];

    [data getBytes:&h2 range:NSMakeRange(5, 1)];

    [data getBytes:&h3 range:NSMakeRange(6, 1)];

    [data getBytes:&h4 range:NSMakeRange(7, 1)];

    int h = (h1 << 24) + (h2 << 16) + (h3 << 8) + h4;

    return CGSizeMake(w, h);

  }

  return CGSizeZero;

}

+(CGSize)downloadGIFImageSizeWithRequest:(NSMutableURLRequest*)request

{

  [request setValue:@"bytes=6-9" forHTTPHeaderField:@"Range"];

  NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

  if(data.length == 4)

  {

    short w1 = 0, w2 = 0;

    [data getBytes:&w1 range:NSMakeRange(0, 1)];

    [data getBytes:&w2 range:NSMakeRange(1, 1)];

    short w = w1 + (w2 << 8);

    short h1 = 0, h2 = 0;

    [data getBytes:&h1 range:NSMakeRange(2, 1)];

    [data getBytes:&h2 range:NSMakeRange(3, 1)];

    short h = h1 + (h2 << 8);

    return CGSizeMake(w, h);

  }

  return CGSizeZero;

}

+(CGSize)downloadJPGImageSizeWithRequest:(NSMutableURLRequest*)request

{

  [request setValue:@"bytes=0-209" forHTTPHeaderField:@"Range"];

  NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

  

  if ([data length] <= 0x58) {

    return CGSizeZero;

  }

  if ([data length] < 210) {// 肯定只有一个DQT字段

    short w1 = 0, w2 = 0;

    [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];

    [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];

    short w = (w1 << 8) + w2;

    short h1 = 0, h2 = 0;

    [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];

    [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];

    short h = (h1 << 8) + h2;

    return CGSizeMake(w, h);

  } else {

    short word = 0x0;

    [data getBytes:&word range:NSMakeRange(0x15, 0x1)];

    if (word == 0xdb) {

      [data getBytes:&word range:NSMakeRange(0x5a, 0x1)];

      if (word == 0xdb) {// 两个DQT字段

        short w1 = 0, w2 = 0;

        [data getBytes:&w1 range:NSMakeRange(0xa5, 0x1)];

        [data getBytes:&w2 range:NSMakeRange(0xa6, 0x1)];

        short w = (w1 << 8) + w2;

        short h1 = 0, h2 = 0;

        [data getBytes:&h1 range:NSMakeRange(0xa3, 0x1)];

        [data getBytes:&h2 range:NSMakeRange(0xa4, 0x1)];

        short h = (h1 << 8) + h2;

        return CGSizeMake(w, h);

      } else {// 一个DQT字段

        short w1 = 0, w2 = 0;

        [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];

        [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];

        short w = (w1 << 8) + w2;

        short h1 = 0, h2 = 0;

        [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];

        [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];

        short h = (h1 << 8) + h2;

        return CGSizeMake(w, h);

      }

    } else {

      return CGSizeZero;

    }

  }

}
@end
